<div id="xcode-cache">
  <.card title={gettext("Analytics")} icon="chart_arcs" data-part="analytics-card">
    <:actions>
      <.button_group size="large">
        <.button_group_item
          patch={"?#{Query.put(@uri.query, "analytics_date_range", "last_7_days")}"}
          label={gettext("7 days")}
          data-selected={@analytics_date_range == "last_7_days"}
        />
        <.button_group_item
          patch={"?#{Query.put(@uri.query, "analytics_date_range", "last_30_days")}"}
          label={gettext("30 days")}
          data-selected={@analytics_date_range == "last_30_days"}
        />
        <.button_group_item
          patch={"?#{Query.put(@uri.query, "analytics_date_range", "last_12_months")}"}
          label={gettext("12 months")}
          data-selected={@analytics_date_range == "last_12_months"}
        />
      </.button_group>
    </:actions>
    <div data-part="widgets">
      <.percentile_dropdown_widget
        id="widget-cache-hit-rate"
        title={
          case {@selected_hit_rate_type, Enum.empty?(@builds)} do
            {"avg", false} -> gettext("Avg. cache hit rate")
            {"p99", false} -> gettext("p99 cache hit rate")
            {"p90", false} -> gettext("p90 cache hit rate")
            {"p50", false} -> gettext("p50 cache hit rate")
            _ -> gettext("Cache hit rate")
          end
        }
        legend_color={
          case @selected_hit_rate_type do
            "p99" -> "p99"
            "p90" -> "p90"
            "p50" -> "p50"
            _ -> "primary"
          end
        }
        description={
          gettext(
            "Cache hit rate represents the percentage of cacheable tasks that were resolved from cache (local or remote) rather than being rebuilt."
          )
        }
        value={
          gettext("%{hit_rate}%",
            hit_rate:
              case @selected_hit_rate_type do
                "p99" -> @hit_rate_p99.total_percentile_hit_rate
                "p90" -> @hit_rate_p90.total_percentile_hit_rate
                "p50" -> @hit_rate_p50.total_percentile_hit_rate
                _ -> @hit_rate_analytics.avg_hit_rate
              end
              |> Decimal.from_float()
              |> Decimal.round(1)
          )
        }
        metrics={
          %{
            avg:
              gettext("%{hit_rate}%",
                hit_rate:
                  @hit_rate_analytics.avg_hit_rate
                  |> Decimal.from_float()
                  |> Decimal.round(1)
              ),
            p99:
              gettext("%{hit_rate}%",
                hit_rate:
                  @hit_rate_p99.total_percentile_hit_rate
                  |> Decimal.from_float()
                  |> Decimal.round(1)
              ),
            p90:
              gettext("%{hit_rate}%",
                hit_rate:
                  @hit_rate_p90.total_percentile_hit_rate
                  |> Decimal.from_float()
                  |> Decimal.round(1)
              ),
            p50:
              gettext("%{hit_rate}%",
                hit_rate:
                  @hit_rate_p50.total_percentile_hit_rate
                  |> Decimal.from_float()
                  |> Decimal.round(1)
              )
          }
        }
        selected_type={@selected_hit_rate_type}
        event_name="select_hit_rate_type"
        phx_click="select_widget"
        phx_value_widget="cache_hit_rate"
        selected={@analytics_selected_widget == "cache_hit_rate"}
        trend_value={
          case @selected_hit_rate_type do
            "p99" -> @hit_rate_p99.trend
            "p90" -> @hit_rate_p90.trend
            "p50" -> @hit_rate_p50.trend
            _ -> @hit_rate_analytics.trend
          end
        }
        trend_label={@analytics_trend_label}
        empty={@hit_rate_analytics.avg_hit_rate == 0}
      />
      <.widget
        title={gettext("Cache downloads")}
        legend_color="secondary"
        description={
          gettext(
            "Cache downloads represents the total size of cache artifacts downloaded from remote storage during the given period."
          )
        }
        value={ByteFormatter.format_bytes(@downloads_analytics.total_size)}
        id="widget-cache-downloads"
        trend_value={@downloads_analytics.trend}
        trend_type={:neutral}
        trend_label={@analytics_trend_label}
        phx_click="select_widget"
        phx_value_widget="cache_downloads"
        selected={@analytics_selected_widget == "cache_downloads"}
        empty={@downloads_analytics.total_size == 0}
      />
      <.widget
        title={gettext("Cache uploads")}
        legend_color="p99"
        description={
          gettext(
            "Cache uploads represents the total size of cache artifacts uploaded to remote storage during the given period."
          )
        }
        value={ByteFormatter.format_bytes(@uploads_analytics.total_size)}
        id="widget-cache-uploads"
        trend_value={@uploads_analytics.trend}
        trend_type={:neutral}
        trend_label={@analytics_trend_label}
        phx_click="select_widget"
        phx_value_widget="cache_uploads"
        selected={@analytics_selected_widget == "cache_uploads"}
        empty={@uploads_analytics.total_size == 0}
      />
    </div>
    <.card_section :if={
      @hit_rate_analytics.avg_hit_rate != 0 or @downloads_analytics.total_size != 0 or
        @uploads_analytics.total_size != 0
    }>
      <div data-part="analytics-chart">
        <.chart
          :if={@analytics_selected_widget == "cache_hit_rate"}
          id="xcode-cache-hit-rate-chart"
          type="line"
          extra_options={
            %{
              legend: %{
                left: "left",
                top: "bottom",
                orient: "horizontal",
                textStyle: %{
                  color: "var:noora-surface-label-secondary",
                  fontFamily: "monospace",
                  fontWeight: 400,
                  fontSize: 10,
                  lineHeight: 12
                },
                icon:
                  "path://M0 6C0 4.89543 0.895431 4 2 4H6C7.10457 4 8 4.89543 8 6C8 7.10457 7.10457 8 6 8H2C0.895431 8 0 7.10457 0 6Z",
                itemWidth: 8,
                itemHeight: 4
              },
              grid: %{
                width: "97%",
                left: "0.4%",
                height: "60%",
                top: "10%"
              },
              xAxis: %{
                boundaryGap: false,
                type: "category",
                axisLabel: %{
                  color: "var:noora-surface-label-secondary",
                  formatter: "fn:toLocaleDate",
                  customValues: [
                    @hit_rate_analytics.dates |> List.first(),
                    @hit_rate_analytics.dates |> List.last()
                  ],
                  padding: [10, 0, 0, 0]
                }
              },
              yAxis: %{
                splitNumber: 4,
                splitLine: %{
                  lineStyle: %{
                    color: "var:noora-chart-lines"
                  }
                },
                axisLabel: %{
                  color: "var:noora-surface-label-secondary",
                  formatter: "{value}%"
                }
              },
              tooltip: %{
                valueFormat: "{value}%"
              }
            }
          }
          series={[
            %{
              color: "var:noora-chart-primary",
              data:
                Enum.zip(
                  @hit_rate_analytics.dates,
                  @hit_rate_analytics.values
                )
                |> Enum.map(&Tuple.to_list/1),
              name: gettext("Average"),
              type: "line",
              smooth: 0.1,
              symbol: "none"
            },
            %{
              color: "var:noora-chart-p99",
              data:
                Enum.zip(
                  @hit_rate_p99.dates,
                  @hit_rate_p99.values
                )
                |> Enum.map(&Tuple.to_list/1),
              name: gettext("p99"),
              type: "line",
              smooth: 0.1,
              symbol: "none"
            },
            %{
              color: "var:noora-chart-p90",
              data:
                Enum.zip(
                  @hit_rate_p90.dates,
                  @hit_rate_p90.values
                )
                |> Enum.map(&Tuple.to_list/1),
              name: gettext("p90"),
              type: "line",
              smooth: 0.1,
              symbol: "none"
            },
            %{
              color: "var:noora-chart-p50",
              data:
                Enum.zip(
                  @hit_rate_p50.dates,
                  @hit_rate_p50.values
                )
                |> Enum.map(&Tuple.to_list/1),
              name: gettext("p50"),
              type: "line",
              smooth: 0.1,
              symbol: "none"
            }
          ]}
          y_axis_min={0}
          y_axis_max={100}
        />
        <.chart
          :if={@analytics_selected_widget != "cache_hit_rate"}
          id="xcode-cache-analytics-chart"
          type="line"
          extra_options={
            %{
              grid: %{
                width: "93%",
                left: "0.4%",
                right: "7%",
                height: "88%",
                top: "5%"
              },
              xAxis: %{
                boundaryGap: false,
                type: "category",
                axisLabel: %{
                  color: "var:noora-surface-label-secondary",
                  formatter: "fn:toLocaleDate",
                  customValues: [
                    @analytics_chart_data.dates |> List.first(),
                    @analytics_chart_data.dates |> List.last()
                  ],
                  padding: [10, 0, 0, 0]
                }
              },
              yAxis: %{
                splitLine: %{
                  lineStyle: %{
                    color: "var:noora-chart-lines"
                  }
                },
                axisLabel: %{
                  color: "var:noora-surface-label-secondary",
                  formatter: @analytics_chart_data.value_formatter
                }
              },
              tooltip: %{
                valueFormat: @analytics_chart_data.value_formatter
              },
              legend: %{
                show: false
              }
            }
          }
          series={[
            %{
              data:
                Enum.zip(
                  @analytics_chart_data.dates,
                  @analytics_chart_data.values
                )
                |> Enum.map(&Tuple.to_list/1),
              name: @analytics_chart_data.name,
              type: "line",
              smooth: 0.1,
              symbol: "none"
            }
          ]}
          y_axis_min={0}
        />
      </div>
    </.card_section>
    <.empty_card_section
      :if={
        @hit_rate_analytics.avg_hit_rate == 0 and @downloads_analytics.total_size == 0 and
          @uploads_analytics.total_size == 0
      }
      title={gettext("No data yet")}
    >
      <:image>
        <img src="/images/empty_line_chart_light.png" data-theme="light" />
        <img src="/images/empty_line_chart_dark.png" data-theme="dark" />
      </:image>
    </.empty_card_section>
  </.card>
  <.card title={gettext("Recent Builds")} icon="dashboard" data-part="recent-builds">
    <:actions>
      <.button
        variant="secondary"
        label={gettext("View more")}
        size="medium"
        navigate={
          ~p"/#{@selected_project.account.name}/#{@selected_project.name}/builds/build-runs"
        }
        disabled={Enum.empty?(@builds)}
      />
    </:actions>
    <.card_section :if={not Enum.empty?(@builds)} data-part="recent-builds-section">
      <div data-part="builds-section">
        <div data-part="builds-chart">
          <.legend
            title={gettext("Cache hit rate")}
            value={
              gettext("%{hit_rate}%",
                hit_rate:
                  @avg_recent_hit_rate
                  |> Decimal.from_float()
                  |> Decimal.round(1)
              )
            }
            style="primary"
          />
          <.chart
            id="recent-builds-hit-rate-chart"
            type="bar"
            extra_options={
              %{
                grid: %{
                  width: "98%",
                  left: "0.4%",
                  right: "7%",
                  height: "88%",
                  top: "5%"
                },
                tooltip: %{
                  valueFormat: "{value}%",
                  dateFormat: "minute"
                },
                xAxis: %{
                  axisLabel: %{show: false},
                  data: @recent_builds_chart_data |> Enum.map(& &1.date)
                },
                yAxis: %{
                  splitLine: %{
                    lineStyle: %{
                      color: "var:noora-chart-lines"
                    }
                  },
                  axisLabel: %{
                    color: "var:noora-surface-label-secondary",
                    formatter: "{value}%"
                  }
                },
                legend: %{
                  show: false
                }
              }
            }
            series={[
              %{
                data: @recent_builds_chart_data,
                name: "Cache Hit Rate",
                type: "bar",
                barMinHeight: 3
              }
            ]}
            y_axis_min={0}
            y_axis_max={100}
            grid_lines
            bar_width={8}
            bar_radius={2}
          />
        </div>
        <.table
          id="builds-table"
          rows={@builds |> Enum.take(7)}
          row_navigate={
            fn build ->
              url(
                ~p"/#{@selected_project.account.name}/#{@selected_project.name}/builds/build-runs/#{build.id}"
              )
            end
          }
        >
          <:col :let={build} label={gettext("Scheme")}>
            <.text_and_description_cell label={build.scheme || "None"} />
          </:col>
          <:col :let={build} label={gettext("Hit Rate")}>
            <.text_cell label={
              gettext("%{hit_rate}%",
                hit_rate:
                  cache_hit_rate(build)
                  |> Decimal.from_float()
                  |> Decimal.round(1)
              )
            } />
          </:col>
          <:col :let={build} label={gettext("Ran by")}>
            <.run_ran_by_badge_cell
              run={build}
              ran_by_name={if build.ran_by_account, do: build.ran_by_account.name}
            />
          </:col>
          <:col :let={build} label={gettext("Duration")}>
            <.text_cell
              label={
                gettext("%{duration}s",
                  duration:
                    (build.duration / 1000)
                    |> Decimal.from_float()
                    |> Decimal.round(1)
                )
              }
              icon="history"
            />
          </:col>
          <:col :let={build} label={gettext("Ran at")}>
            <.text_cell sublabel={Tuist.Utilities.DateFormatter.from_now(build.inserted_at)} />
          </:col>
        </.table>
      </div>
    </.card_section>
    <div :if={Enum.empty?(@builds)} data-part="empty-builds">
      <.empty_card_section
        title={gettext("No data yet")}
        get_started_href="https://docs.tuist.dev/en/guides/develop/build/cache"
        data-part="empty-builds-table-card-section"
      >
        <:image>
          <img src="/images/empty_table_light.png" data-theme="light" />
          <img src="/images/empty_table_dark.png" data-theme="dark" />
        </:image>
      </.empty_card_section>
    </div>
  </.card>
</div>
